# #人工智能NLP-Agent数字人项目-02-日程提醒任务工单V1.1-20250215
import re
import logging
import sqlite3
from typing import Any
from langchain.tools import BaseTool

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class MyTimer(BaseTool):
    name: str = "MyTimer"
    description: str = ("用于设置日程。接受3个参数，格式为: HH:MM|YYYYYYY|事项内容，所用标点符号必须为标准的英文字符。"
                        "其中，'HH:MM' 表示时间（24小时制），'YYYYYYY' 表示循环规则（每位代表一天，从星期一至星期日，1为循环，0为不循环，"
                        "如'1000100'代表每周一和周五循环），'事项内容' 是提醒的具体内容。返回例子：15:15|0000000|提醒主人叫咖啡")
    uid: int = 0

    async def _arun(self, *args: Any, **kwargs: Any) -> Any:
        # 用例中没有用到 arun，抛出异常明确告知未实现
        raise NotImplementedError("异步方法 _arun 未实现")

    def _run(self, para: str) -> str:
        try:
            # 拆分输入字符串
            time, repeat_rule, content = self._split_input(para)
            # 验证输入参数
            self._validate_input(time, repeat_rule, content)
            # 数据库操作
            with self._get_db_connection() as conn:
                self._insert_into_database(conn, time, repeat_rule, content)
            return "日程设置成功"
        except ValueError as ve:
            return str(ve)
        except sqlite3.Error as se:
            logging.error(f"数据库错误: {se}")
            return f"数据库错误: {se}"

    def _split_input(self, para: str) -> tuple:
        parts = para.split("|")
        if len(parts) != 3:
            error_msg = f"输入格式错误，当前字符串{para} len:{len(parts)}。请按照 HH:MM|YYYYYYY|事项内容 格式提供参数，如：15:15|0000001|提醒主人叫咖啡。"
            logging.error(error_msg)
            raise ValueError(error_msg)
        return (parts[0].strip("'"), parts[1].strip("'"), parts[2].strip("'"))

    def _validate_input(self, time: str, repeat_rule: str, content: str):
        self._validate_time(time)
        self._validate_repeat_rule(repeat_rule)
        self._validate_content(content)

    def _validate_time(self, time: str):
        if not re.match(r'^[0-2][0-9]:[0-5][0-9]$', time):
            error_msg = "时间格式错误。请按照'HH:MM'格式提供时间。"
            logging.error(error_msg)
            raise ValueError(error_msg)

    def _validate_repeat_rule(self, repeat_rule: str):
        if not re.match(r'^[01]{7}$', repeat_rule):
            error_msg = "循环规则格式错误。请提供长度为7的0和1组成的字符串。"
            logging.error(error_msg)
            raise ValueError(error_msg)

    def _validate_content(self, content: str):
        if not isinstance(content, str) or not content:
            error_msg = "事项内容必须为非空字符串。"
            logging.error(error_msg)
            raise ValueError(error_msg)

    def _get_db_connection(self):
        return sqlite3.connect('timer.db')

    def _insert_into_database(self, conn: sqlite3.Connection, time: str, repeat_rule: str, content: str):
        cursor = conn.cursor()
        try:
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS timer (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    time TEXT NOT NULL,
                    repeat_rule TEXT NOT NULL,
                    content TEXT NOT NULL,
                    uid INTEGER NOT NULL
                )
            ''')
            cursor.execute("INSERT INTO timer (time, repeat_rule, content, uid) VALUES (?, ?, ?, ?)",
                           (time, repeat_rule, content, self.uid))
            conn.commit()
            logging.info("日程已成功插入数据库")
        except sqlite3.Error as e:
            conn.rollback()
            raise e


if __name__ == "__main__":
    my_timer = MyTimer()
    result = my_timer._run("15:15|0000001|提醒主人叫咖啡")
    print(result)